package com.dly.hope.controller;

import com.dly.hope.constant.ExceptionConstant;
import com.dly.hope.constant.R;
import com.dly.hope.servce.JwtService;
import com.dly.hope.utils.ExceptionPropertiesUtil;
import com.dly.hope.vo.UserDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @author linyu.dai
 * @creat 2022/8/26 15:04:51
 */
public class BaseController {

    @Resource
    private JwtService jwtService;

    @Value("${jwt.header}")
    private String jwtHeader;

    public <T> ResponseEntity<T> operate(Supplier<T> sp,BindingResult br){
        validateFiled(br);
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(sp.get());
    }

    public <T> ResponseEntity<T> operate(Supplier<T> sp){
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(sp.get());
    }

    public <T> R<T> success(){
        return R.ok("成功");
    }

    public <T> R<T> successDate(T date){
        return R.ok(date, "成功");
    }

    /**
     * @Author linyu.dai
     * @Description 获取请求 request
     * @Date 2022/8/27 15:24
     * @Param []
     * @return javax.servlet.http.HttpServletRequest
     */
    public HttpServletRequest request(){
        return Optional.of((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).
                orElseThrow(() -> ExceptionPropertiesUtil.getException(ExceptionConstant.SERVLET_NULL))
                .getRequest();
    }

    /**
     * @Author linyu.dai
     * @Description 获取当前用户
     * @Date 2022/8/27 15:50
     * @Param []
     * @return com.dly.hope.vo.UserDTO
     */
    public UserDTO currentUser(){
        HttpServletRequest request = request();
        //重请求头里获取token
        String token = request.getHeader(jwtHeader);
        //如果不存在重参数里面获取
        if(Objects.isNull(token)){
            token = request.getParameter(jwtHeader);
        }
        UserDTO userDTO = jwtService.unSign(token);
        return userDTO;
    }

    /**
     * @Author linyu.dai
     * @Description 获取用户的id
     * @Date 2022/8/27 16:16
     * @Param []
     * @return java.lang.String
     */
    public String getCurrentUserId(){
        return currentUser().getId();
    }

    /**
     * @Author linyu.dai
     * @Description 校验参数
     * @Date 2022/8/27 20:42
     * @Param [br]
     * @return void
     */
    public void validateFiled(BindingResult br){

        if(br.hasErrors()){
            throw new IllegalArgumentException(br
                    .getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .distinct()
                    .collect(Collectors.toList())
                    .toString()
            );
        }

    }
}
